<?php
/**
 * @version     1.0.0
 * @package     com_geotrails
 * @copyright   Copyright (C) 2011. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Verbier Technologies Sarl
 */

// no direct access
defined('_JEXEC') or die;

// Component Helper
jimport('joomla.application.component.helper');

/**
 * Geotrails Component Route Helper
 *
 * @static
 * @package		Vsb.Site
 * @subpackage	com_geotrails
 * @since 1.5
 */
abstract class GeotrailsHelperRoute {

	protected static $lookup;

	/**
	 * @param	int	The route of the newsfeed
	 */
	public static function getGeotrailsRoute($id, $alias = false, $item = false) {
	
		//Create the link
		$link = 'index.php?option=com_geotrails&view=fiche&id='.$id;
		
		if (strlen($alias)) {
			$link .= ':'.JFilterOutput::stringURLSafe($alias);
		}
		
		if (!$item) {
			$item = self::_findItem();
		}
		
		if ($item) {
			$link .= '&Itemid='.$item;
		}
		
		return $link;
	}
	
	protected static function _findItem() {
		$application = JFactory::getApplication();
		$menus       = $application->getMenu('site');

		// Prepare the reverse lookup array.
		if (self::$lookup === null) {
			self::$lookup = array();

			$component	= JComponentHelper::getComponent('com_geotrails');
			$items		= $menus->getItems('component_id', $component->id);
			
			foreach ($items as $item) {
				if (isset($item->query) && isset($item->query['view'])) {
					$view = $item->query['view'];
					
					if (!isset(self::$lookup[$view])) {
						self::$lookup[$view] = array();
					}

					if (isset($item->query['id'])) {
						self::$lookup[$view][$item->query['id']] = $item->id;
					}
				}
			}
		}

		$active = $menus->getActive();
		
		if ($active) {
			return $active->id;
		}

		return null;
	}	
}